package com.dkts.oil.service.impl.address;

import com.dkts.oil.service.impl.AddressPlanV2ServiceImpl;
import com.dkts.oil.web.vo.request.SiteSelectionRequest;
import com.dkts.oil.web.vo.response.AddressPlanResponse;
import org.apache.commons.lang3.tuple.Pair;
import org.locationtech.jts.geom.Geometry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WcgySitesHelper {

    @Qualifier("addressPlanV2ServiceImpl")
    @Autowired
    AddressPlanV2ServiceImpl addressPlanV2Service;
    public List<AddressPlanResponse.Site> addressPlan(SiteSelectionRequest request, Geometry planGeometry, List<Geometry> wcgyGeometries, String name) {
        List<AddressPlanResponse.Site> wcgySites = new ArrayList<>();

        if (wcgyGeometries == null || wcgyGeometries.size() == 0){
            return wcgySites;
        }

        //外场供油中心 应该在机场内部。如果内部没有就取离机场中心点最近的点
        List<Pair<Geometry, Double>> sortedWithDistance = wcgyGeometries.stream()
                .map(g -> Pair.of(g, g.distance(request.point)))
                .sorted(Comparator.comparingDouble(Pair::getRight))
                .collect(Collectors.toList());
        List<Geometry> placedSites = new ArrayList<>();
        for (int i = 0; i < sortedWithDistance.size(); i++){
            Pair<Geometry, Double> pair = sortedWithDistance.get(i);
            AddressPlanResponse.Site site = addressPlanV2Service.pickSiteFromGrid(
                    placedSites,
                    request.getAreaConfig().getFuelSupplyCenterArea(),
                    name,
                    request.getCenterPoint(),
                    pair.getLeft(),
                    i + 1, request.getPoint()
            );
            wcgySites.add(site);
            if (wcgySites.size() > 3){
                break;
            }
        }
        return wcgySites;

    }
}
